package furns.dao.impl;

import furns.dao.BasicDAO;
import furns.dao.FurnDAO;
import furns.entity.Furn;

import java.util.List;


//DAO层实现类。该类主要通过SQL语句对数据库进行操作。
public class FurnDAOImpl extends BasicDAO<Furn> implements FurnDAO {
    @Override
    public List<Furn> queryFurns() {
        //假如数据库表中的字段和javabean类中的属性名不一样，那么就需要使用别名来映射。如：img_path imgPath
        String sql = "select id, name, maker, price, sales, stock, img_path imgPath from furn";
        return queryMulti(sql, Furn.class);
    }

    @Override
    public int saveFurn(Furn furn) {
        String sql = "insert into furn(id, name, maker, price, sales, stock, img_path) values(null, ?, ?, ?, ?, ?, ?)";
        return update(sql, furn.getName(), furn.getMaker(), furn.getPrice(), furn.getSales(), furn.getStock(), furn.getImgPath());
    }

    @Override
    public int deleteFurnById(int id) {
        String sql = "delete from furn where id = ?";
        return update(sql, id);
    }

    @Override
    public Furn queryFurnById(int id) {
        String sql = "select id, name, maker, price, sales, stock, img_path imgPath from furn where id = ?";
        return querySingle(sql, Furn.class, id);
    }

    @Override
    public int updateFurn(Furn furn) {
        String sql = "update furn set name = ?, maker = ?, price = ?, sales = ?, stock = ?, img_path = ? where id = ?";
        return update(sql, furn.getName(), furn.getMaker(), furn.getPrice(), furn.getSales(), furn.getStock(), furn.getImgPath(), furn.getId());
    }

    @Override
    public int getTotalRow() {
        String sql = "select count(*) from furn";
//        return (Integer) queryScalar(sql);    //不能直接使用integer进行转换，会导致类型转换错误
        return ((Number) queryScalar(sql)).intValue();
    }

    @Override
    public List<Furn> getPageItems(int begin, int pageSize) {
        String sql = "select id, name, maker, price, sales, stock, img_path imgPath from furn limit ?, ?";
        return queryMulti(sql, Furn.class, begin, pageSize);
    }

    @Override
    public int getPageTotalCountByName(String name) {
        String sql = "select count(*) from furn where name like ?";
        //Number是所有数值类型的父类。使用模糊查询，只要名字中含有name表示的字符串，都可以查出来。
        return ((Number) queryScalar(sql,"%" + name + "%")).intValue();
    }

    @Override
    public List<Furn> getPageItemsByName(String name, int begin, int pageSize) {
        String sql = "select id, name, maker, price, sales, stock, img_path imgPath from furn where name like ? limit ?, ?";
        return queryMulti(sql, Furn.class, "%" + name + "%", begin, pageSize);
    }
}
